<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once BASEPATH . '/libraries/Model.php';

class ActiveModel extends Model {
	
	protected $_tableName;
	protected $_className;
	
	function __construct()
	{
	    parent::__construct();
	    $this->_ar = new $this->_className;
	}
	
	/*
		Function: _rowToRecord
		Convert a row retrived from the database into the appropriate
        ActiveRecord class
	*/
	private function _rowToRecord($row)
	{
		$activerecord = new $this->_className;
		$activerecord->populate($row);
		return $activerecord;
	}
	
	/*
		Function: find
		Finds all records that match a given criteria
	*/
	public function find($criteria=null)
	{
	    $results = array();
		if ($criteria) $this->db->where($criteria);
		$q = $this->db->get($this->_tableName);
		foreach($q->result() as $row) {
			$results[] = $this->_rowToRecord($row);
		}
		return $results;
	}
	
	/*
	    Function: update
	    Updates a batch of records

	    Arguments:
	        ids - ID of each record to update
	*/
	public function update($data, $ids)
	{
	    $key_field = $this->_ar->getKeyField();
        $this->db->where_in($key_field, $ids);
        $this->db->update($this->_tableName, $data);
	}
}